package com.application.chiettinhdienluc.ui;

import java.util.Calendar;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

import com.actionbarsherlock.app.SherlockFragment;
import com.application.chiettinhdienluc.R;
import com.application.chiettinhdienluc.app.MainApplication;
import com.application.chiettinhdienluc.data.GlobalData;



public class KhachHangInfoFragment extends SherlockFragment 
{
	private final String TAG = KhachHangInfoFragment.class.getSimpleName();
	private final static int DIALOG_DATE_TIME_PICKER 		= 0;
	private Resources res;
	private TextView tv_userinfo;
	
	
	private int mYear = 1980;
	private int mMonth = 1;
	private int mDay = 1;
	private int mcur_Year;
	
	private EditText edt_number_of_bangtinh;
	private EditText edt_request_id;
	private EditText edt_dpn;
	private EditText edt_address;
	private EditText edt_phonenumber;
	private TextView datetime_receive;
	private Spinner spin_trangthai_hoso;
	private Spinner spin_donvi_dautu;
	
	private String[] arrayTrangThaiHoSoId;
	private String[] arrayTrangThaiHoSoName;
	private String trangThaiHoSoId;
	
	private String[] arrayDonViDauTuId;
	private String[] arrayDonViDauTuName;
	private String donViDauTuId;
	
	private boolean UpdateListenerIsRegistered = false;
	private UpdateListener listener = null;
	
	public EditText getEdt_dpn() {
		return edt_dpn;
	}
	
	public EditText getEdt_address() {
		return edt_address;
	}

	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getActivity().getWindow().setBackgroundDrawable(null);
	}

	/**
	 * The Fragment's UI
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.khachhang_info, container, false);
		spin_trangthai_hoso = (Spinner)v.findViewById(R.id.spin_trangthai_hoso);
		spin_donvi_dautu = (Spinner)v.findViewById(R.id.spin_donvi_dautu);
		edt_number_of_bangtinh = (EditText)v.findViewById(R.id.edt_number_of_bangtinh);
		edt_request_id = (EditText)v.findViewById(R.id.edt_request_id);
		edt_dpn = (EditText)v.findViewById(R.id.edt_dpn);
		edt_address = (EditText)v.findViewById(R.id.edt_address);
		edt_phonenumber = (EditText)v.findViewById(R.id.edt_phonenumber);
		datetime_receive = (TextView)v.findViewById(R.id.datetime_receive);
		
		return v;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		res = getResources();
		
		listener = new UpdateListener();
		
		datetime_receive.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				UserInfoDialogFragment dialogFrag = UserInfoDialogFragment.getNewInstance(DIALOG_DATE_TIME_PICKER, KhachHangInfoFragment.this);
				if(dialogFrag != null)
				{
					if(dialogFrag.isVisible())
						dialogFrag.dismiss();
					dialogFrag.show(getFragmentManager(), "dialog");
				}
			}
		});
		
		//TrangThaiHoSo spinner
		arrayTrangThaiHoSoId = res.getStringArray(R.array.array_trangthaihoso_id);
		arrayTrangThaiHoSoName = res.getStringArray(R.array.array_trangthaihoso_name);
		ArrayAdapter<String> adapterTrangThaiHoSo = new ArrayAdapter<String>(getActivity(), R.layout.spinnertext, arrayTrangThaiHoSoName){
			@Override      
	        public boolean isEnabled(int position) {
				//disable last item
				if(position == this.getCount()-1){
					return false;
				}
				else{
					return true;
				}
			}
		};           
		adapterTrangThaiHoSo.setDropDownViewResource(R.layout.spiner_item);  
		spin_trangthai_hoso.setAdapter(adapterTrangThaiHoSo);
		spin_trangthai_hoso.setOnItemSelectedListener(new OnItemSelectedListener() {         
		    @Override
		    public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {		    	
		    	trangThaiHoSoId = arrayTrangThaiHoSoId[position];
		    }

		    @Override
		    public void onNothingSelected(AdapterView<?> arg0) {}
		   });
		
		
		//DonViDauTu spinner
		arrayDonViDauTuId = res.getStringArray(R.array.array_donvidautu_id);
		arrayDonViDauTuName = res.getStringArray(R.array.array_donvidautu_name);
		ArrayAdapter<String> adapterDonViDauTu = new ArrayAdapter<String>(getActivity(), R.layout.spinnertext, arrayDonViDauTuName);           
		adapterDonViDauTu.setDropDownViewResource(R.layout.spiner_item);  
		spin_donvi_dautu.setAdapter(adapterDonViDauTu);
		spin_donvi_dautu.setOnItemSelectedListener(new OnItemSelectedListener() {         
		    @Override
		    public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {		    	
		    	donViDauTuId = arrayDonViDauTuId[position];
		    	
//		    	GlobalData.globalChietTinh.set_DonViDauTu(donViDauTuId);
//		    	MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_DonViDauTu(donViDauTuId);
		    	Intent i = new Intent();
//				i.setAction("com.application.chiettinhdienluc.ui.maDonViDauTu_change");
				i.setAction("com.application.chiettinhdienluc.ui.UpdateLocalChietTinhModelResultInfo");
				i.putExtra("UpdateDataForResultTab", true);
				MainApplication.getAppContext().sendBroadcast(i);
		    }

		    @Override
		    public void onNothingSelected(AdapterView<?> arg0) {}
		   });
		
		try
		{
			// get the current date
			final Calendar c = Calendar.getInstance();
			mcur_Year = c.get(Calendar.YEAR);
			
//			String [] spit = GlobalData.userInfo.dob.split("/");				
			mDay = c.get(Calendar.DAY_OF_MONTH);
			mMonth = c.get(Calendar.MONTH) + 1;
			mYear = c.get(Calendar.YEAR);				
		}
		catch(Exception e){}	

		updateDisplay();
		
		updateDisplayInfoGlobal();
	}
	
	// the callback received when the user "sets" the date in the dialog
	private DatePickerDialog.OnDateSetListener mDateSetListener =
			new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, 
				int monthOfYear, int dayOfMonth) {
			mYear = year;
			// Month is 0 based so add 1
			mMonth = monthOfYear + 1;
			mDay = dayOfMonth;
			updateDisplay();
		}
	};
	
	private void updateDisplay() {
		datetime_receive.setText(
				new StringBuilder()								
				.append(mDay).append('/')
				// Month is 0 based so add 1
				.append(mMonth).append('/')
				.append(mYear).append(' '));
	}
	
	static public class UserInfoDialogFragment extends DialogFragment {
		private KhachHangInfoFragment userInfoFrag = null;

		public static UserInfoDialogFragment getNewInstance(int id, KhachHangInfoFragment userInfoF) {
			UserInfoDialogFragment frag = new UserInfoDialogFragment(userInfoF);
			Bundle args = new Bundle();
			args.putInt("id", id);
			frag.setArguments(args);
			return frag;
		}
		
		public UserInfoDialogFragment(KhachHangInfoFragment userInfoF) {
			this.userInfoFrag = userInfoF;
		}
		
		// Empty constructor
		public UserInfoDialogFragment() {
			
		}

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			int id = getArguments().getInt("id");
			Dialog dialog = null;
			Resources res = getResources();

			// Dismiss dialog if app is restarted
			try {
				if (userInfoFrag == null || savedInstanceState != null) {
					this.dismiss();
					return super.onCreateDialog(savedInstanceState);
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			
			switch (id) {

			case DIALOG_DATE_TIME_PICKER:
			{    	
				try {
					if(!TextUtils.isEmpty(GlobalData.globalChietTinh.get_NgayND().trim()))
					{
						String [] spit = GlobalData.globalChietTinh.get_NgayND().trim().split("/");				
						userInfoFrag.mDay = Integer.parseInt(spit[0]);
						userInfoFrag.mMonth = Integer.parseInt(spit[1]);
						userInfoFrag.mYear = Integer.parseInt(spit[2]);
						
						dialog = new DatePickerDialog(getActivity(),
								userInfoFrag.mDateSetListener,
								userInfoFrag.mYear, userInfoFrag.mMonth - 1, userInfoFrag.mDay);
					}	
					else
					{
						dialog = new DatePickerDialog(getActivity(),
								userInfoFrag.mDateSetListener,
								userInfoFrag.mYear, userInfoFrag.mMonth - 1, userInfoFrag.mDay);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			break; 	

			default:
				break;
			}
			return dialog;
		}
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		if (!UpdateListenerIsRegistered && listener != null) {
			IntentFilter intentFilter = new IntentFilter();
			intentFilter.addAction("com.application.chiettinhdienluc.ui.RefreshUserInfo");
			intentFilter.addAction("com.application.chiettinhdienluc.ui.SaveUserInfo");
			intentFilter.addAction("com.application.chiettinhdienluc.ui.UpdateLocalChietTinhModelUserInfo");
			getActivity().registerReceiver(listener, intentFilter);
			UpdateListenerIsRegistered = true;
		}
		
//		updateDisplayInfoGlobal();
	}
	
	private void updateDisplayInfoGlobal()
	{
		if(MainTabFragmentActivity.getiMode() == MainTabFragmentActivity.MODE_EDITABLE)
		{
			edt_number_of_bangtinh.setText(GlobalData.globalChietTinh.get_MaBanChietTinh());
			edt_request_id.setText(GlobalData.globalChietTinh.get_MaYeuCauKhieuNai());
			edt_dpn.setText(GlobalData.globalChietTinh.get_TenKhachHang());
			edt_address.setText(GlobalData.globalChietTinh.get_DiaChi());
			edt_phonenumber.setText(GlobalData.globalChietTinh.get_DienThoaiDichVu());
			if(!TextUtils.isEmpty(GlobalData.globalChietTinh.get_NgayND()))
				datetime_receive.setText(GlobalData.globalChietTinh.get_NgayND());
			else
				updateDisplay();
			
			if(!TextUtils.isEmpty(GlobalData.globalChietTinh.get_TrangThaiHoSo()))
			{
				for(int i = 0; i < arrayTrangThaiHoSoId.length;i++)
				{
					if(GlobalData.globalChietTinh.get_TrangThaiHoSo().equals(arrayTrangThaiHoSoId[i]))
					{
						spin_trangthai_hoso.setSelection(i);
						break;
					}
				}
			}
			else
			{
				GlobalData.globalChietTinh.set_TrangThaiHoSo(arrayTrangThaiHoSoId.length > 0 ? arrayTrangThaiHoSoId[0] : "");
				spin_trangthai_hoso.setSelection(0);
			}
			
			if(!TextUtils.isEmpty(GlobalData.globalChietTinh.get_DonViDauTu()))
			{
				for(int i = 0; i < arrayDonViDauTuId.length;i++)
				{
					if(GlobalData.globalChietTinh.get_DonViDauTu().equals(arrayDonViDauTuId[i]))
					{
						spin_donvi_dautu.setSelection(i);
						break;
					}
				}
			}
			else
			{
				GlobalData.globalChietTinh.set_DonViDauTu(arrayDonViDauTuId.length > 0 ? arrayDonViDauTuId[0] : "");
				spin_donvi_dautu.setSelection(0);
			}
		}	
		else if(MainTabFragmentActivity.getiMode() == MainTabFragmentActivity.MODE_NEW_INPUT)
		{
			edt_number_of_bangtinh.setText(GlobalData.globalChietTinh.get_MaBanChietTinh());
			edt_request_id.setText(GlobalData.globalChietTinh.get_MaYeuCauKhieuNai());
			edt_dpn.setText(GlobalData.globalChietTinh.get_TenKhachHang());
			edt_address.setText(GlobalData.globalChietTinh.get_DiaChi());
			edt_phonenumber.setText(GlobalData.globalChietTinh.get_DienThoaiDichVu());
			if(!TextUtils.isEmpty(GlobalData.globalChietTinh.get_NgayND()))
				datetime_receive.setText(GlobalData.globalChietTinh.get_NgayND());
			else
				updateDisplay();
			
			if(!TextUtils.isEmpty(GlobalData.globalChietTinh.get_TrangThaiHoSo()))
			{
				for(int i = 0; i < arrayTrangThaiHoSoId.length;i++)
				{
					if(GlobalData.globalChietTinh.get_TrangThaiHoSo().equals(arrayTrangThaiHoSoId[i]))
					{
						spin_trangthai_hoso.setSelection(i);
						break;
					}
				}
			}
			else
			{
				GlobalData.globalChietTinh.set_TrangThaiHoSo(arrayTrangThaiHoSoId.length > 0 ? arrayTrangThaiHoSoId[0] : "");
				spin_trangthai_hoso.setSelection(0);
			}
			
			if(!TextUtils.isEmpty(GlobalData.globalChietTinh.get_DonViDauTu()))
			{
				for(int i = 0; i < arrayDonViDauTuId.length;i++)
				{
					if(GlobalData.globalChietTinh.get_DonViDauTu().equals(arrayDonViDauTuId[i]))
					{
						spin_donvi_dautu.setSelection(i);
						break;
					}
				}
			}
			else
			{
				GlobalData.globalChietTinh.set_DonViDauTu(arrayDonViDauTuId.length > 0 ? arrayDonViDauTuId[0] : "");
				spin_donvi_dautu.setSelection(0);
			}
			
			updateDisplay();
		}
	}
	
	protected class UpdateListener extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			try {
				if(intent != null && !TextUtils.isEmpty(intent.getAction()))
				{
					Log.i("Line break", System.getProperty("line.separator"));
					String action = intent.getAction();
					boolean updateDataForResultTab = false;
					if(!TextUtils.isEmpty(action))
					{
						if(action.equals("com.application.chiettinhdienluc.ui.RefreshUserInfo"))
							updateDisplayInfoGlobal();
						else if(action.equals("com.application.chiettinhdienluc.ui.SaveUserInfo"))
						{
							GlobalData.globalChietTinh.set_MaBanChietTinh(edt_number_of_bangtinh.getText().toString().trim());
							
							String maYeuCau = edt_request_id.getText().toString().trim();
							if (maYeuCau.isEmpty())
								maYeuCau = "0";
							
							GlobalData.globalChietTinh.set_MaYeuCauKhieuNai(maYeuCau);
							
							GlobalData.globalChietTinh.set_TenKhachHang(edt_dpn.getText().toString().replaceAll(System.getProperty("line.separator"), " ").trim());
							
							GlobalData.globalChietTinh.set_DiaChi(edt_address.getText().toString().replaceAll(System.getProperty("line.separator"), " ").trim());
							GlobalData.globalChietTinh.set_DienThoaiDichVu(edt_phonenumber.getText().toString().trim());
							GlobalData.globalChietTinh.set_NgayND(datetime_receive.getText().toString().trim());
							GlobalData.globalChietTinh.set_TrangThaiHoSo(trangThaiHoSoId);
							GlobalData.globalChietTinh.set_DonViDauTu(donViDauTuId);
							
							if(MainApplication.getAppContext() != null)
							{
								Intent broadcastIntent = new Intent();
								broadcastIntent.setAction("com.application.chiettinhdienluc.ui.SaveKhaoSatInfo");
								MainApplication.getAppContext().sendBroadcast(broadcastIntent);
							}
							
//							if(MainApplication.getAppContext() != null)
//							{
//								Intent broadcastIntent = new Intent();
//								broadcastIntent.setAction("com.application.chiettinhdienluc.ui.SaveVattuInfo");
//								MainApplication.getAppContext().sendBroadcast(broadcastIntent);
//							}
						}	
						else if(action.equals("com.application.chiettinhdienluc.ui.UpdateLocalChietTinhModelUserInfo"))
						{
							updateDataForResultTab = intent != null ? intent.getBooleanExtra("UpdateDataForResultTab", false) : false;
							
							MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_MaBanChietTinh(edt_number_of_bangtinh.getText().toString());
							MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_MaYeuCauKhieuNai(edt_request_id.getText().toString());
							MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_TenKhachHang(edt_dpn.getText().toString());
							MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_DiaChi(edt_address.getText().toString());
							MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_DienThoaiDichVu(edt_phonenumber.getText().toString());
							MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_NgayND(datetime_receive.getText().toString().trim());
							MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_TrangThaiHoSo(trangThaiHoSoId);
							MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_DonViDauTu(donViDauTuId);
							
							if(MainApplication.getAppContext() != null)
							{
								Intent broadcastIntent = new Intent();
								broadcastIntent.setAction("com.application.chiettinhdienluc.ui.UpdateLocalChietTinhModelKhaoSatInfo");
								if(updateDataForResultTab) broadcastIntent.putExtra("UpdateDataForResultTab", true);
								MainApplication.getAppContext().sendBroadcast(broadcastIntent);
							}
						}
					}	
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
	public void onPause() {
		try {
			if (UpdateListenerIsRegistered && listener != null) {
				getActivity().unregisterReceiver(listener);
				UpdateListenerIsRegistered = false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onPause();
	}


//	@Override
//	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//		// TODO Auto-generated method stub
//		inflater.inflate(R.menu.action_bar_menu_user_info, menu);
//	}
	
	
}